package kd;

import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class KeyAgree{
    public KeyAgree(){}
    public static SecretKeySpec KeyAgree(String a,String b) throws Exception{
        // 读取对方的DH公钥
        FileInputStream f1=new FileInputStream(a);
        ObjectInputStream b1=new ObjectInputStream(f1);
        PublicKey  pbk=(PublicKey)b1.readObject( );
//读取自己的DH私钥
        FileInputStream f2=new FileInputStream(b);
        ObjectInputStream b2=new ObjectInputStream(f2);
        PrivateKey  prk=(PrivateKey)b2.readObject( );
        // 执行密钥协定
        KeyAgreement ka=KeyAgreement.getInstance("DH");
        ka.init(prk);
        ka.doPhase(pbk,true);
        //生成共享信息
        byte[ ] s=ka.generateSecret();
        byte []sb = new byte[24];
        System.arraycopy(s, 0, sb, 0, 24);
        System.out.println("共享秘钥：");
        for(int i=0;i<sb.length;i++){
            System.out.print(sb[i]+" ");
        }
        System.out.println();
        SecretKeySpec k=new  SecretKeySpec(sb,"DESede");
        return k;
    }
}